<template>
  <div class="">
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="" prop="">
          <el-input v-model="queryParams.destroyEquityCardName" placeholder="NFR名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="70px">
          <el-select v-model="queryParams.status" placeholder="请选择" size="small">
            <el-option v-for="item in statusOptions" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery" size="mini">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="listBox">
      <div class="listBox_head">
        <el-button type="primary" @click="configureTo(1)" :disabled="productIds.length>0?false:true">配置奖励</el-button>
        <el-button type="primary" @click="configureTo(2)" :disabled="productIds.length>0?false:true">批量启用</el-button>
        <el-button type="primary" @click="configureTo(3)" :disabled="productIds.length>0?false:true">批量停用</el-button>
      </div>
      <el-table ref="multipleTable" v-loading="loading" :data="tableList" stripe border row-key="id"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true" width="55" fixed="left">
        </el-table-column>
        <el-table-column label="序号" align="center" type="index" width="64px" fixed="left" />
        <el-table-column label="可销毁时间" align="center" prop="time" width="154px" fixed="left" />
        <!-- <el-table-column label="可销毁时间" align="center" width="160" fixed="left">
          <template slot-scope="scope">
            <p>{{scope.row.startTime}}</p>
            <p>{{scope.row.endTime}}</p>
          </template>
        </el-table-column> -->
        <el-table-column label="NFR名称" align="center" prop="destroyEquityCardName" :show-overflow-tooltip="true"
          width="120" fixed="left" />
        <el-table-column label="销毁奖励（椰分）" align="center" prop="award" />
        <el-table-column label="铸造数量" align="center" prop="total" width="120" />
        <el-table-column label="持有数量" align="center" prop="holdTotal" width="120" />
        <el-table-column label="虚拟打入" align="center" prop="shenyeAccountTotal" />
        <el-table-column label="销毁数量" align="center" prop="destroyTotal" />
        <el-table-column label="奖励统计（椰分）" align="center" prop="awardTotal" />
        <el-table-column label="状态" align="center" width="120">
          <template slot-scope="scope">
            <dict-tag :options="statusOptions" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 批量操作弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <div v-if="status==1">
        <el-form ref="form" :model="rewardFrom" :rules="rules" :label-width="labelWidth">
          <el-form-item label="卡权益配置" prop="awardType">
            <el-select v-model="rewardFrom.awardType" placeholder="请选择权益" :style="{width: inputWidth}">
              <el-option v-for="dict in awardTypeOption" :key="dict.id" :label="dict.value" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="奖励数量" prop="award">
            <el-input v-model="rewardFrom.award" placeholder="填写奖励数量" :style="{width: inputWidth}"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogClose">取 消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="submitForm(1)">确认提交</el-button>
        </span>
      </div>
      <div v-if="status==2">
        <el-form ref="form" :model="rewardFrom" :rules="rules" :label-width="labelWidth">
          <el-form-item label="活动时间：" prop="date">
            <el-date-picker v-model="rewardFrom.date" type="datetimerange" format="yyyy-MM-dd HH"
              value-format="yyyy-MM-dd HH" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogClose">取 消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="submitForm(2)">确认提交</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    destroyActivityList,
    destroyActivityAward,
    destroyActivityEnd,
    destroyActivityStart,
  } from "@/api/blindBox/factoryConfig";
  import ExportExcelButton from "@/components/ExportExcelButton/index";
  export default {
    // dicts: ['equity_card_issue_type', 'equity_card_sell_status'],
    name: "",
    components: {
      ExportExcelButton
    },
    data() {
      return {
        labelWidth: '120px',
        inputWidth: '280px',
        dialogTitle: '',
        dialogVisible: false,
        // 遮罩层
        loading: false,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        tableList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          destroyEquityCardName: '', //销毁数字权益卡名称
          status: '', //活动状态 destroy_activity_status 1 启用 2停用
        },
        status: '1', //1配置奖励 2：批量启用 3：批量停用
        productIds: [], // 选中数组
        statusOptions: [], //活动状态数组
        awardTypeOption: [{
            id: '1',
            value: '椰分'
          },
          // {id:'2',value:'CoCo'}
        ],
        saveLoading: false,
        rewardFrom: { //参数
          award: '', //销毁奖励
          awardType: '1', //奖励类型（1椰分 2coco）
          idList: [], //id数组
          date: [], //销毁时间（校验用）
          startTime: '', //销毁开始时间 精确到小时 yyyy-MM-dd HH:mm:ss
          endTime: '', //销毁结束时间 精确到小时 yyyy-MM-dd HH:mm:ss
        },
        // 表单校验
        rules: {
          awardType: [{
            required: true,
            message: "请选择奖励类型",
            trigger: ["change"]
          }],
          award: [{
            required: true,
            message: "填写奖励数量",
            trigger: ["change", "blur"]
          }],
          date: [{
            required: true,
            message: "请选择可销毁时间",
            trigger: ["change"]
          }],
        },
      };
    },
    computed: {
      ExportParams() {
        const params = {
          ...this.queryParams,
        };
        return params;
      },
    },
    created() {
      this.getDict();
      this.getList();
    },
    methods: {
      //获取字典
      getDict() {
        var dictType = "destroy_activity_status ";
        this.$getSelectList(dictType)
          .then((res) => {
            var arr = [{
              id: "",
              value: "全部",
            }, ];
            this.statusOptions = arr.concat(res.result[0].dictList);
            // this.statusOptions = res.result[0].dictList;
          })
          .finally(() => {

          });
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        destroyActivityList(this.queryParams).then(response => {
          this.tableList = response.result.records;
          this.total = response.result.total;
          this.tableList = this.tableList.map(item => {
            item.time = item.startTime + item.endTime
            Object.keys(item).forEach(key => {
              if (item[key] === '') {
                item[key] = '-'
              }
            })
            return item
          })
          this.loading = false;
        });
      },
      // 表单重置
      reset() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          destroyEquityCardName: '', //销毁数字权益卡名称
          status: '', //活动状态 destroy_activity_status 1 启用 2停用
        }
        // this.resetForm("form");
        this.handleQuery()
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.reset();
        this.handleQuery();
        // this.$refs.multipleTable.clearSelection(); //清空表格多选选中状态
      },
      dialogClose(){
          this.$refs['form'].resetFields();
          this.dialogVisible = false
      },
      /** 按钮操作 */
      configureTo(status) {
        this.rewardFrom = { //参数
            award: '', //销毁奖励
            awardType: '1', //奖励类型（1椰分 2coco）
            idList: [], //id数组
            date: [], //销毁时间（校验用）
            startTime: '', //销毁开始时间 精确到小时 yyyy-MM-dd HH:mm:ss
            endTime: '', //销毁结束时间 精确到小时 yyyy-MM-dd HH:mm:ss
          },
          this.status = status
        if (status == 1) {
          this.dialogTitle = '配置奖励'
          this.dialogVisible = true
        } else if (status == 2) {
          this.dialogTitle = '批量启用'
          this.dialogVisible = true
        } else {
          this.dialogTitle = '批量停用'
          this.$confirm('是否确认停用销毁?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let data = {
                idList: this.productIds
            }
            destroyActivityEnd(data).then(response => {
              this.$message.success('停用成功');
              this.getList()
              this.dialogVisible = false
              this.saveLoading = false
            }).catch(() => {
              this.saveLoading = false
            });
            
          }).catch(() => {});
        }

      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.productIds = selection.map(item => item.id)
        console.log(this.productIds)
      },
      submitForm(status) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.rewardFrom.idList = this.productIds
            if (status == 1) { //配置奖励
              this.saveLoading = true
              destroyActivityAward(this.rewardFrom).then(response => {
                this.$message.success('配置成功');
                this.getList()
                this.dialogVisible = false
                setTimeout(()=>{
                  this.saveLoading = false
                },800)
              }).catch(() => {
                this.saveLoading = false
              });
            } else if (status == 2) { //批量启用
              this.rewardFrom.startTime = this.rewardFrom.date[0] + ':00:00'
              this.rewardFrom.endTime = this.rewardFrom.date[1] + ':00:00'
              this.saveLoading = true
              destroyActivityStart(this.rewardFrom).then(response => {
                this.$message.success('启用成功');
                this.getList()
                this.dialogVisible = false
                // this.saveLoading = false
                setTimeout(()=>{
                  this.saveLoading = false
                },800)
              }).catch(() => {
                this.saveLoading = false
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    }
  };

</script>
<style scoped>
  .head {
    box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px 0;
  }

  .listBox {
    box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px;
    margin-top: 10px;
  }

  .listBox_head {
    width: 100%;
    display: flex;
    align-items: center;
    padding-bottom: 20px;
  }

  .img_box {
    width: 80px;
    height: 80px;
  }

  .time_box {
    cursor: pointer;
  }

  .time_box:hover {
    color: #1890FF;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    padding-top: 10px;
  }

</style>
